package ar.com.ford.it.fullEconomics.logic;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Collection;
import ar.com.ford.it.fullEconomics.FullEconomicsPrs;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.persistence.dao.RequestItemDao;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp01Part;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp02Commodity;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesr01Request;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesr02Requestitm;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesr03Agreement;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesr04Agreemitem;
import ar.com.ford.it.fullEconomics.persistence.dto.Teess01Supplier;
import ar.com.ford.it.fullEconomics.struct.RequestFindStruct;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.persistence.PersistenceUtil;
import com.ford.it.logging.ILogger;
import com.ford.it.logging.Level;
import com.ford.it.logging.LogFactory;
import com.ford.it.persistence.PersistenceException;

public class RequestItemLogic {

    private static final String CLASS_NAME = CommodityLogic.class.getName();
    private static final ILogger log = LogFactory.getInstance().getLogger(
            CLASS_NAME);

    /**
     * crea un nuevo item, debe contener el request al que pertenece
     * 
     * @param item
     * @param user
     * @throws FullEconomicsException
     */
    public void createRequestItem(Teesr02Requestitm item,
                                  FullEconomicsWslxUser user)
            throws FullEconomicsException {

        String METHOD_NAME = "createRequestItem";
        log.entering(CLASS_NAME, METHOD_NAME);

        RequestItemDao dao = new RequestItemDao();
        AgreementItemLogic agreemItemLogic = new AgreementItemLogic();
        String[] fields = new String[2];
        Object[] values = new Object[2];

        try {
            PersistenceUtil.newTransaction();
            Teesr04Agreemitem agreemItem = new Teesr04Agreemitem();
            Teesr03Agreement agreement = new Teesr03Agreement();
            agreement.setTeess01Supplier(item.getTeesr01Request()
                    .getTeess01Supplier());
            agreement.setEesr03PlantCodeC(item.getEesr02PlantCodeC());
            agreemItem.setEesr04AgritmTypeCodeC(item.getEesr02ReqitmTypeCodeC());
            agreemItem.setTeesp04Supply(item.getTeesp04Supply());
            agreemItem.setTeesp02Commodity(item.getTeesp02Commodity());
            agreemItem.setNcas012VehicleVw(item.getNcas012VehicleVw());
            agreemItem.setEesr04PlantCodeC(item.getEesr02PlantCodeC());
            agreemItem.setTeesr03Agreement(agreement);
            agreemItem.setEesr04AgritmEffectiveDateY(new Timestamp(System
                    .currentTimeMillis()));
            agreemItem = agreemItemLogic.findPrevAgreementItem(agreemItem);
            if (item.getEesr02ReqitmIncrPercentC() != null) {
                if (agreemItem == null) {
                    throw new FullEconomicsException(
                            new Exception(),
                            FullEconomicsPrs.MessageErrors.AgreementItem.NO_PREV_AGREEMENT);
                } else {
                    item.setEesr02ReqitmNewpriceAmounA(agreemItem
                            .getEesr04AgritmNewpriceAmounA().multiply(
                                    new BigDecimal(1).add(item
                                            .getEesr02ReqitmIncrPercentC()
                                            .divide(new BigDecimal(100)))));
                }
            } else {
                if (agreemItem != null) {
                    item.setEesr02ReqitmIncrPercentC(agreemItem
                            .getEesr04AgritmNewpriceAmounA().subtract(
                                    item.getEesr02ReqitmNewpriceAmounA())
                            .divide(agreemItem.getEesr04AgritmNewpriceAmounA(),
                                    5, BigDecimal.ROUND_HALF_EVEN));
                }
            }
            fields[0] = "eesr02PlantCodeC";
            values[0] = user.getTeesg01Plant();
            fields[1] = "teesr01Request";
            values[1] = item.getTeesr01Request();
            Integer lastCode = dao.getMax(new Teesr02Requestitm(), fields,
                    values, "eesr02ReqitmNumberK");
            item.setEesr02ReqitmNumberK(lastCode + 1);
            item.setEesr02CreateS(new Timestamp(System.currentTimeMillis()));
            item.setEesr02LastUpdtS(new Timestamp(System.currentTimeMillis()));
            item.setEesr02LastUpdtUserC(user.getId());
            item.setEesr02CreateUserC(user.getId());
            item.setEesr02PlantCodeC(user.getTeesg01Plant());

            dao.createRequestItem(item);
            PersistenceUtil.commitTransaction();

        } catch (PersistenceException pe) {

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "PersistenceException", pe);
            try {
                PersistenceUtil.rollbackTransaction();
            } catch (PersistenceException rollbackEx) {
                rollbackEx.printStackTrace();
            }

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Create Request item Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.RequestItem.CREATE);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * Guarda los cambio hechos en el item
     * 
     * @param item
     * @param user
     * @throws FullEconomicsException
     */
    public void updateRequestItem(Teesr02Requestitm item,
                                  FullEconomicsWslxUser user)
            throws FullEconomicsException {

        String METHOD_NAME = "updateRequestItem";
        log.entering(CLASS_NAME, METHOD_NAME);

        RequestItemDao dao = new RequestItemDao();
        VehiclelinLogic lineLogic = new VehiclelinLogic();
        AgreementItemLogic agreemItemLogic = new AgreementItemLogic();
        Teesr02Requestitm workingCopy = null;

        try {
            PersistenceUtil.newTransaction();
            item.setEesr02PlantCodeC(user.getTeesg01Plant());
            Teesr04Agreemitem agreemItem = new Teesr04Agreemitem();
            Teesr03Agreement agreement = new Teesr03Agreement();
            agreement.setTeess01Supplier(item.getTeesr01Request()
                    .getTeess01Supplier());
            agreement.setEesr03PlantCodeC(item.getEesr02PlantCodeC());
            agreemItem.setEesr04AgritmTypeCodeC(item.getEesr02ReqitmTypeCodeC());
            agreemItem.setTeesp04Supply(item.getTeesp04Supply());
            agreemItem.setTeesp02Commodity(item.getTeesp02Commodity());
            agreemItem.setNcas012VehicleVw(item.getNcas012VehicleVw());
            agreemItem.setEesr04PlantCodeC(item.getEesr02PlantCodeC());
            agreemItem.setTeesr03Agreement(agreement);
            agreemItem.setEesr04AgritmEffectiveDateY(new Timestamp(System
                    .currentTimeMillis()));
            agreemItem = agreemItemLogic.findPrevAgreementItem(agreemItem);
            if (item.getEesr02ReqitmIncrPercentC() != null) {
                if (agreemItem == null) {
                    throw new FullEconomicsException(
                            new Exception(),
                            FullEconomicsPrs.MessageErrors.AgreementItem.NO_PREV_AGREEMENT);
                } else {
                    item.setEesr02ReqitmNewpriceAmounA(agreemItem
                            .getEesr04AgritmNewpriceAmounA().multiply(
                                    new BigDecimal(1).add(item
                                            .getEesr02ReqitmIncrPercentC()
                                            .divide(new BigDecimal(100)))));
                }
            } else {
                if (agreemItem != null) {
                    item.setEesr02ReqitmIncrPercentC(agreemItem
                            .getEesr04AgritmNewpriceAmounA().subtract(
                                    item.getEesr02ReqitmNewpriceAmounA())
                            .divide(agreemItem.getEesr04AgritmNewpriceAmounA(),
                                    5, BigDecimal.ROUND_HALF_EVEN));
                }
            }
            workingCopy = dao.getRequestItemForUpdate(item.getTeesr01Request(),
                    item.getEesr02ReqitmNumberK(), user.getTeesg01Plant());
            workingCopy.setNcas012VehicleVw(lineLogic
                    .getVehiclelinUpdateByPk(item.getNcas012VehicleVw()));
            workingCopy.setEesr02ReqitmStatusCodeC(item
                    .getEesr02ReqitmStatusCodeC());
            workingCopy.setEesr02ReqitmIncrPercentC(item
                    .getEesr02ReqitmIncrPercentC());
            workingCopy.setEesr02ReqitmNewpriceAmounA(item
                    .getEesr02ReqitmNewpriceAmounA());
            workingCopy.setEesr02CurrencyCodeC(item.getEesr02CurrencyCodeC());
            workingCopy.setEesr02ReqitmEcolevelDateY(item
                    .getEesr02ReqitmEcolevelDateY());
            workingCopy.setEesr02ReqitmEffectiveDateY(item
                    .getEesr02ReqitmEffectiveDateY());
            workingCopy.setEesr02LastUpdtS(new Timestamp(System
                    .currentTimeMillis()));
            workingCopy.setEesr02LastUpdtUserC(user.getId());
            PersistenceUtil.commitTransaction();

        } catch (PersistenceException pe) {

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "PersistenceException", pe);
            try {
                PersistenceUtil.rollbackTransaction();
            } catch (PersistenceException rollbackEx) {
                rollbackEx.printStackTrace();
            }

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Update Request item Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.RequestItem.UPDATE);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * busca todos los items de un request
     * 
     * @param request
     * @return
     * @throws FullEconomicsException
     */
    public Collection<Teesr02Requestitm> findRequestItems(Teesr01Request request)
            throws FullEconomicsException {
        String METHOD_NAME = "findRequestItems";
        log.entering(CLASS_NAME, METHOD_NAME);
        Collection<Teesr02Requestitm> items = null;
        RequestItemDao dao = new RequestItemDao();
        String[] fields = new String[2];
        Object[] values = new Object[2];

        try {
            fields[0] = "eesr02PlantCodeC";
            values[0] = request.getEesr01PlantCodeC();
            fields[1] = "teesr01Request";
            values[1] = request;

            items = dao.findAll(new Teesr02Requestitm(), fields, values);
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find request items Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.RequestItem.FIND);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return items;

    }

    public Collection<Teesr02Requestitm> findRequestItems(
                                                          RequestFindStruct findStruct)
            throws FullEconomicsException {

        String METHOD_NAME = "findRequestItems";
        log.entering(CLASS_NAME, METHOD_NAME);

        RequestItemDao dao = new RequestItemDao();
        Collection<Teesr02Requestitm> ret;
        try {
            Teess01Supplier supplier = new Teess01Supplier();
            supplier.setEess01PlantCodeC(findStruct.getPlant());
            supplier.setEess01SupplierClassCodeC(findStruct.getSupplierClass());
            supplier.setEess01SupplierCodeC(findStruct.getSupplierCode());
            Teesp02Commodity commodity = null;
            Teesp01Part part = null;
            if (findStruct.getCommodity() != -1) {
                commodity = new Teesp02Commodity();
                commodity.setEesp02PlantCodeC(findStruct.getPlant());
                commodity.setEesp02CommodityNumberK(findStruct.getCommodity());
            } else if (!findStruct.getPartClass().equals("-1")) {
                part = new Teesp01Part();
                part.setEesp01PlantCodeC(findStruct.getPlant());
                part.setEesp01PartClassCodeC(findStruct.getPartClass());
                part.setEesp01PartPrefixCodeC(findStruct.getPrefix());
                part.setEesp01PartBaseCodeC(findStruct.getBase());
                part.setEesp01PartSuffixCodeC(findStruct.getSuffix());
            }
            ret = dao.findRequestItems(findStruct, supplier, commodity, part);
        } catch (PersistenceException pe) {

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "PersistenceException", pe);
            try {
                PersistenceUtil.rollbackTransaction();
            } catch (PersistenceException rollbackEx) {
                rollbackEx.printStackTrace();
            }

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find Request Items Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.Request.FIND);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return ret;
    }

    /**
     * borra el item
     * 
     * @param item
     * @throws FullEconomicsException
     */
    public void deleteRequestItem(Teesr02Requestitm item)
            throws FullEconomicsException {
        String METHOD_NAME = "findRequestItems";
        log.entering(CLASS_NAME, METHOD_NAME);
        RequestItemDao dao = new RequestItemDao();
        try {
            PersistenceUtil.newTransaction();
            dao.deleteRequestItem(item);
            PersistenceUtil.commitTransaction();
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find request items Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.RequestItem.DELETE);
        }
        log.exiting(CLASS_NAME, METHOD_NAME);
    }

}
